package com.stu.stusystem.config;

import com.stu.stusystem.mapper.system.StuMapper;
import com.stu.stusystem.model.em.Jurisdiction;
import com.stu.stusystem.model.system.StuUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

/**
 * @author cxt
 * @date 2020/9/10
 */
@Slf4j
public class MyShiroRealm extends AuthorizingRealm {

    private StuMapper stuMapper;

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        StuUser user = (StuUser) principals.getPrimaryPrincipal();
        log.info("登陆授权,user={}", user);
        // 角色列表
        Set<String> roles = new HashSet<>();
        // 功能列表
        Set<String> menus = new HashSet<>();
        if (user.getJurisdiction() == Jurisdiction.ADMIN) {
            info.addRole("admin");
            info.addStringPermission("*:*:*");
        } else {
//            roles = roleService.selectRoleKeys(user.getUserId());      // 查询角色表
//            menus = menuService.selectPermsByUserId(user.getUserId()); // 查询数据库(角色表和菜单表)，角色id对应菜单权限id

            // 角色加入AuthorizationInfo认证对象
            info.setRoles(roles);
            // 权限加入AuthorizationInfo认证对象
            info.setStringPermissions(menus);
        }
        return info;
    }

    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String account = (String) token.getPrincipal();
        StuUser stuUser = stuMapper.selectOne(new StuUser().setAccount(account));
        if (stuUser == null) {
            return null;
        }
        return new SimpleAuthenticationInfo(stuUser, stuUser.getPassword(), getName());
    }

    @Autowired
    public void setStuMapper(StuMapper stuMapper) {
        this.stuMapper = stuMapper;
    }
}
